package saxion.speelveld.spaceengineer.controller;

import java.util.ArrayList;

import saxion.speelveld.spaceengineer.R;
import saxion.speelveld.spaceengineer.model.Game;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class GameRowAdapter extends ArrayAdapter<Game>
{

	private Context context;

	private ArrayList<Game> gameList;

	public GameRowAdapter(Context context, ArrayList<Game> games)
	{
		super(context, R.layout.loadgame_list_row, games);
		this.context = context;
		this.gameList = games;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null)
		{
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.loadgame_list_row, parent, false);
		}

		TextView tvGameName = (TextView) convertView.findViewById(R.id.tvGameName);
		TextView tvGameTicks = (TextView) convertView.findViewById(R.id.tvGameTimeInTicks);

		// tvGameName.setText("Save Game #" + (position + 1));
		tvGameName.setText("Save Game #" + gameList.get(position).getGameId() + " playing on "
			+ gameList.get(position).getDifficulty().toString());
		tvGameTicks.setText(gameTicksToTime(gameList.get(position).getGameTime()));
		return convertView;
	}

	private String gameTicksToTime(int gameTime)
	{
		String returnTime = "playtime: ";
		int seconds = gameTime * 5;
		int secondsInDay = 86400;
		int secondsInHour = 3600;
		int secondsInMinute = 60;

		if (seconds > secondsInDay)
		{
			int amountOfDays = seconds / secondsInDay;
			returnTime += amountOfDays + " days and ";
			seconds = seconds - secondsInDay * amountOfDays;
		}
		int hoursPlayed = seconds / secondsInHour;
		seconds = seconds - (hoursPlayed * secondsInHour);

		int minutesPlayed = seconds / secondsInMinute;
		seconds = seconds - (minutesPlayed * secondsInMinute);

		returnTime += twoDigitString(hoursPlayed) + ":";

		returnTime += twoDigitString(minutesPlayed) + ":";

		returnTime += twoDigitString(seconds);

		return returnTime;
	}

	private String twoDigitString(int number)
	{
		if (number == 0)
		{
			return "00";
		}
		else if (number < 10)
		{
			return number + "0";
		}
		else
		{
			return Integer.toString(number);
		}
	}
}
